package com.casic.worklog.controller;

import com.alibaba.fastjson.JSONObject;
import com.casic.worklog.jwt.JwtUtil;
import com.casic.worklog.model.Employee;
import com.casic.worklog.service.EmployeeService;
import com.casic.worklog.util.BsResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class LoginShiroTest {

    @Autowired
    EmployeeService employeeService;

    /**
     * 用户登录接口
     * @param user user
     * @param request request
     * @return string
     */
    @GetMapping("/login")
    @ResponseBody
    public BsResult login(Employee user, HttpServletRequest request) {

        // 根据用户名和密码创建 Token
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        // 获取 subject 认证主体
        Subject subject = SecurityUtils.getSubject();

        try{
            // 开始认证，这一步会跳到我们自定义的 Realm 中(shiro)
            subject.login(token);


            //jwt
            user = employeeService.findByUsername(user.getUsername());
            String jwtToken = JwtUtil.sign(user.getUsername(),user.getId()+"",36000000);
            request.getSession().setAttribute("user", user);
            return BsResult.success(user).put("token" , jwtToken);

        }catch(Exception e){
            e.printStackTrace();
            request.getSession().setAttribute("user", user);
            return BsResult.error(500,"用户名或密码错误！");
        }
    }
}